<?php 
/**
 * Класс, который реализовует Extjs Grid
 *
 */

class FRM_View_Ext_Grid extends FRM_View_Ext_Abstract
{
	/**
	 * Enter description here...
	 *
	 * @var int
	 */
	protected $parentField = "id_parent";

	/**
	 * Enter description here...
	 *
	 * @param string $parentField
	 */
	public function setParentField ($parentField){
		$this->parentField = $parentField;
	}

	/**
	 * Enter description here...
	 *
	 * @var int
	 */
	protected $baseParams = array();

	public function render(){

		$this->preRender();

		// Reader
		$reader = new PhpExt_Data_JsonReader();
		$reader -> setTotalProperty('totalCount');
		$reader		-> setRoot('data');
		$reader		-> setId('id');

		// ColumnModel
		$colModel = new PhpExt_Grid_ColumnModel();

		foreach ($this->items as $item){
			$name=	(isset($item['name']))?$item['name']:'';
			$label=	(isset($item['label']))?$item['label']:$name;
			$id=	(isset($item['id']))?$item['id']:$name;
			$width=	(isset($item['width']))?$item['width']:150;
			$sort=(isset($item['sort']))?$item['sort']:true;
			$fixed=(isset($item['fixed']))?$item['fixed']:false;
			$isBool=(isset($item['type']) && $item['type']=="Checkbox")?true:false;

			$reader -> addField( new PhpExt_Data_FieldConfigObject($name));
			if (isset($confObj)) unset($confObj);
			$confObj = new PhpExt_Grid_ColumnConfigObject($label);
			$confObj -> setDataIndex($name)
			-> setId($id)
			-> setWidth($width)
			-> setSortable($sort)
			-> setFixed($fixed);
			if ($isBool)
			{
				$confObj->setRenderer(PhpExt_Javascript::inlineStm("function(val) {
            if(val==1) {
               return 'Да'; }
            else {
               return 'Нет'; }
            }"));
			}

			$colModel->addColumn($confObj);
		}

		// Store

		$http = new PhpExt_Data_HttpProxy();
		$http -> setUrl($this->url);

		$store = new PhpExt_Data_Store();
		$store -> setProxy($http)
		-> setReader($reader)
		-> setRemoteSort(true)
		-> setBaseParams($this->baseParams);

		//ToolBar
		$tbItem = new PhpExt_Toolbar_Item();
		$tbItem -> setPressed(true)
		-> setEnableToggle(true)
		-> setText('Show Preview')
		-> setCls('x-btn-text-icon details')
		-> setToggleHandler('toggleDetails');

		$tb = new PhpExt_Toolbar_PagingToolbar();
		$tb -> setPageSize(25)
		-> setStore($store)
		-> setDisplayInfo(true)
		-> setDisplayMessage('Показано {0} - {1} с {2}')
		-> setEmptyMessage('Пусто');


		//Select Model
		$sm = new PhpExt_Grid_RowSelectionModel();

		//Top ToolBar
		$addHandler = new PhpExt_Handler();
		$addHandler = PhpExt_Javascript::inlineStm("function() {".self::$controller.".currentId=0; 
		var dv = editForm.findByType('dataview'); for (var i=0;i<dv.length;i++)
		{
			dv[i].store.baseParams.id=".self::$controller.".currentId;
		}
		editWindow.show(this);  
		//rvOptions.params.id=0; 
		editForm.form.reset();
			if (typeof(tree) == 'object')	{editForm.form.items.get('hidden_".$this->parentField."').setValue(tree.getSelectionModel().getSelectedNode().attributes.".$this->parentField.")};
		}");

		$editHandler = new PhpExt_Handler();
		$editHandler = PhpExt_Javascript::inlineStm("function() { var m = grid.getSelections();  if(m.length == 1) {".self::$controller.".currentId=m[0].get('id'); editWindow.show(this);
		var galleries = editForm.findByType('dataview'); 
		for (var i=0;i<galleries.length;i++)
		{
			galleries[i].store.baseParams.id=".self::$controller.".currentId;
		}
		//rvOptions.params.id=".self::$controller.".currentId; 
		editForm.form.load( { url : '/".self::$module."/".self::$controller."/edit', params : { id : ".self::$controller.".currentId} , waitMsg : 'Подождите...'} );} else { Ext.MessageBox.alert('Информация', 'Выберите только один элемент'); }}");

		$removeHandler = new PhpExt_Handler();
		$removeHandler = PhpExt_Javascript::inlineStm("function() {
      var m = grid.getSelections();
      if(m.length > 0) {
         Ext.MessageBox.confirm('Информация', 'Вы действительно хотите удалить выбранные элементы?', function(btn) {
            if(btn == 'yes') {
               var jsonData = '[{'; for(var i = 0, len = m.length; i < len; i++) {
                  var ss = '\"' + i + '\":\"' + m[i].get('id') + '\"'; if(i == 0) {
                     jsonData = jsonData + ss; }
                  else {
                     jsonData = jsonData + ',' + ss; }
                  store.remove(m[i]); }
               jsonData = jsonData + '}]'; new Ext.data.Store( {
                  autoLoad : true, baseParams : {
                     'delete':jsonData}
                  , failure : function(form, action) {
                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
                  , proxy : new Ext.data.HttpProxy( {
                     url : '/".self::$module."/".self::$controller."/delete'}
                  ), remoteSort : false}
               ); }
            }
         );
         }
      else {
         Ext.MessageBox.alert('Информация', 'Нет вы браных элементов');
         }
      }");
		if (count(self::$langs)){


			$langCheckHandler = new PhpExt_Handler();
			$langCheckHandler = PhpExt_Javascript::inlineStm("function(item) {
	      defaultLang = item.text;
	      store.baseParams.lang = item.id;
	      store.load( {
	         params : {
	            start : 0,
	         	limit : 25}
	         }
	      );
	      Ext.getCmp('pages-win-lang').setText('Язык: <b>' + defaultLang + '</b>');
	      };");


			if ($this->currentLang)
			{
				$langs = array();
				foreach (parent::$langs as $k=>$v) {
					$langs[]=array("id"=>$k, "text"=>$v);
				}
				$langMenu = new PhpExt_Toolbar_MenuButton();
				$langMenu ->setText(PhpExt_Javascript::inlineStm("'Язык: <b>' + defaultLang + ' </b>'"));
				$langMenu ->setMenu(PhpExt_Javascript::inlineStm('{ defaults : { handler : langCheck}, items : '.Zend_Json_Encoder::encode($langs).'}'));
				$langMenu ->setId('pages-win-lang');
			}
		}
		$tbar = new PhpExt_Toolbar_Toolbar();
		$tbar ->addButton("add","Добавить",self::$js."ext/resources/images/default/dd/drop-add.gif",$addHandler);
		$tbar ->addButton("edit","Редактировать",self::$js."ext/resources/images/default/grid/edit.gif",$editHandler);
		$tbar ->addButton("remove","Удалить",self::$js."ext/resources/images/default/grid/remove.gif",$removeHandler);
		if ($this->currentLang && count(self::$langs))
		{
			$tbar ->addItem("lang",$langMenu);
		}

		$vievConfig =  new PhpExt_Config_ConfigObject(array('forceFit'=>true));

		// Grid
		$grid = new PhpExt_Grid_GridPanel();
		$grid->setStore($store)
		->setAutoWidth(true)
		->setAutoHeight(false)
		->setViewConfig(PhpExt_Javascript::inlineStm("{forceFit : true}"))
		->setTopToolbar($tbar)
		->setId(self::$controller.'-grid-id')
		->setTrackMouseOver(true)
		->setSelectionModel($sm)
		->setBottomToolbar($tb)
		->setLoadMask(true)
		->setColumnModel($colModel)
		->setHeader(false)
		->setTitle("Array Grid");
		
		$stlo = new PhpExt_Data_StoreLoadOptions(array('start'=>0,'limit'=>25));

		PhpExt_Ext::AddOnReady(
		(count(self::$langs))?PhpExt_Javascript::assignNew("defaultLang", "'".parent::$langs[$this->currentLang]."'"):null,
		(count(self::$langs))?PhpExt_Javascript::assignNew("langCheck", $langCheckHandler):null,
		$colModel->getJavascript(false,'cm'),
		$store->getJavascript(false, "store"),
		$store->load($stlo),
		$grid->getJavascript(false,"grid")
		);
	}
}